﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GlxRRSDB.ReportDataSetTableAdapters;
using GlxRRSDB;
using GlxRRSMain.Utils;
using GlxRRSMain.Common;
using GlxRRSDB.Data;


namespace GlxRRSMain.UserControls
{
    public partial class ImportBOExDataControl : UserControl
    {
        private const int COLUMN_CINEMA_IDX = 0; // cinema name
        private const int COLUMN_DATE_IDX = 3; // full date
        private const int COLUMN_FILM_TITLE_IDX = 4; // film name
        private const int COLUMN_SCREEN_NUM_IDX = 5; // screen number
        private const int COLUMN_TICKET_TYPE_IDX = 6; // ticket type
        private const int COLUMN_SESSION_IDX = 7; // session id
        private const int COLUMN_ADMIT_IDX = 8;
        private const int COLUMN_BO_IDX = 9;

        //
        private tblBORevenueTableAdapter x_tblBORevenueTableAdapter = new tblBORevenueTableAdapter();
        private tblFilmRevenueTableAdapter x_tblFilmRevenueTableAdapter = new tblFilmRevenueTableAdapter();
        private tblFilmTableAdapter x_tblFilmTableAdapter = new tblFilmTableAdapter();
        private tblSessionTableAdapter x_tblSessionTableAdapter = new tblSessionTableAdapter();
        private tblTicketRevenueTableAdapter x_tblTicketRevenueTableAdapter = new tblTicketRevenueTableAdapter();

        private System.Data.DataSet x_DataSet;

        public ImportBOExDataControl()
        {
            InitializeComponent();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            DataTable dtTable = x_DataSet.Tables[0];
            int cachedCinemaID = 0;
            DateTime cachedDateTime = new DateTime();
            string cachedFilm = "";
            int cachedScreen = 0;
            Dictionary<string, int> cachedSession = new Dictionary<string, int>();
            ImportTicketTypeData cachedTicketTypeData = new ImportTicketTypeData(); //
            //
            for (int rowLoop = 1; rowLoop < dtTable.Rows.Count; rowLoop++)
            {
                // read admit + BO; always exist
                string strAdmits = dtTable.Rows[rowLoop][COLUMN_ADMIT_IDX].ToString();
                int admits = int.Parse(strAdmits);
                string strBORevenue = dtTable.Rows[rowLoop][COLUMN_BO_IDX].ToString();
                int boRevenue = int.Parse(strBORevenue);
                // read cinema id/ cinema name
                string cinemaName = dtTable.Rows[rowLoop][COLUMN_CINEMA_IDX].ToString();
                if (cinemaName.ToLower().Contains("nguyen du"))
                {
                    cachedCinemaID = CINEMA.NGUYEN_DU;
                }
                else if (cinemaName.ToLower().Contains("nguyen trai"))
                {
                    cachedCinemaID = CINEMA.NGUYEN_TRAI;
                }
                else if (cinemaName.ToLower().Contains("tan binh"))
                {
                    cachedCinemaID = CINEMA.TAN_BINH;
                }
                else if (cinemaName.ToLower().Contains("total"))
                {
                    continue;
                }
                // read date
                string strDate = dtTable.Rows[rowLoop][COLUMN_DATE_IDX].ToString();
                if (strDate.ToLower().Contains("total"))
                {
                    // do insert db
                    insertBORevenue(cachedCinemaID, admits, boRevenue, cachedDateTime);
                    // insert ticket type data then reset value
                    insertTicketRevenue(cachedCinemaID, cachedTicketTypeData, cachedDateTime);
                    cachedTicketTypeData = new ImportTicketTypeData();
                    continue;
                }
                else if (strDate.ToLower() != "")
                {
                    cachedDateTime = DateTime.Parse(strDate);
                }
                // read film
                string strFilm = dtTable.Rows[rowLoop][COLUMN_FILM_TITLE_IDX].ToString();
                if (strFilm.ToLower().Contains("total"))
                {
                    insertFilmRevenue(cachedCinemaID, cachedFilm, admits, boRevenue, cachedDateTime);
                    continue;
                }
                else if (strFilm.ToLower() != "")
                {
                    cachedFilm = strFilm;
                }
                // read screen
                string strScreen = dtTable.Rows[rowLoop][COLUMN_SCREEN_NUM_IDX].ToString();
                if (strScreen.ToLower().Contains("total"))
                {
                    // insert session
                    insertSession(cachedCinemaID, cachedScreen, cachedSession, boRevenue, cachedDateTime);
                    cachedSession = new Dictionary<string, int>(); // reset all value
                    continue;
                }
                else if (strScreen.ToLower() != "")
                {
                    cachedScreen = int.Parse(strScreen);
                }
                // read ticket type
                string strTicketType = dtTable.Rows[rowLoop][COLUMN_TICKET_TYPE_IDX].ToString();
                if (strTicketType.ToLower().Contains("total"))
                {
                    // update cache ticket type
                    updateTicketTypeData(cachedTicketTypeData, strTicketType, admits, boRevenue);
                    continue;
                }
                // read session
                string strSession = dtTable.Rows[rowLoop][COLUMN_SESSION_IDX].ToString();
                if (strSession != "")
                {
                    if (cachedSession.ContainsKey(strSession))
                    {
                        int currentAdmits = cachedSession[strSession];
                        currentAdmits += admits;
                        cachedSession[strSession] = currentAdmits;
                    }
                    else
                    {
                        cachedSession[strSession] = admits;
                    }
                }
            }
            MessageBox.Show("Imported total:" + dtTable.Rows.Count + " rows");
        }

        private void insertTicketRevenue(int cachedCinemaID, ImportTicketTypeData cachedTicketTypeData, DateTime cachedDateTime)
        {
            cachedTicketTypeData.CinemaID = cachedCinemaID;
            cachedTicketTypeData.Date = cachedDateTime;
            x_tblTicketRevenueTableAdapter.Insert(cachedTicketTypeData);
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            importFileDialog.Filter = "Excel (.xlsx)|*.xlsx|All Files (*.*)|*.*";
            importFileDialog.FilterIndex = 1;
            importFileDialog.Multiselect = false;

            // Call the ShowDialog method to show the dialog box.
            DialogResult userClickedOK = importFileDialog.ShowDialog();

            // Process input if the user clicked OK.
            if (userClickedOK == DialogResult.OK)
            {
                // Open the selected file to read.
                textBox1.Text = importFileDialog.FileName;
                loadDataGrid(textBox1.Text);
            }
        }
        private void loadDataGrid(string path)
        {
            try
            {
                x_DataSet = FileHelper.getDataSetFromExcel(path);
                dataGridView1.DataSource = x_DataSet.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void insertBORevenue(int cinemaID, int admits, int bo, DateTime date)
        {
            x_tblBORevenueTableAdapter.Insert(cinemaID, admits, bo, date);
        }

        private void insertFilmRevenue(int cachedCinemaID, string cachedFilm, int admits, int boRevenue, DateTime date)
        {
            int filmId = insertOrUpdateFilmByFilmTitle(cachedFilm, date);
            // insert film revenue
            x_tblFilmRevenueTableAdapter.Insert(cachedCinemaID, filmId, admits, boRevenue, date);
        }

        private int insertOrUpdateFilmByFilmTitle(string filmTitle, DateTime date)
        {
            int filmId = -1;
            if (x_tblFilmTableAdapter.GetData().Where(f => f.FilmTitle == filmTitle).ToList().Count == 0)
            {
                // insert new film
                int id = x_tblFilmTableAdapter.Insert(filmTitle, date, date, "A");
                if (id > 0)
                {
                    ReportDataSet.tblFilmRow a1 = x_tblFilmTableAdapter.GetData()
                                               .Where(f => f.FilmTitle == filmTitle)
                                               .First();
                    filmId = a1.ID;
                }
                return filmId;
            }
            // insert or update
            ReportDataSet.tblFilmRow existFilm = x_tblFilmTableAdapter.GetData()
                                           .Where(f => f.FilmTitle == filmTitle)
                                           .First();
            if (existFilm == null)
            {
                // insert new film
                int id = x_tblFilmTableAdapter.Insert(filmTitle, date, date, "A");
                if (id > 0)
                {
                    ReportDataSet.tblFilmRow a1 = x_tblFilmTableAdapter.GetData()
                                               .Where(f => f.FilmTitle == filmTitle)
                                               .First();
                    filmId = a1.ID;
                }
            }
            else
            {
                filmId = existFilm.ID;
                // update time
                // check start date
                if (existFilm.StartDate == DateTime.MinValue || existFilm.StartDate > date)
                {
                    existFilm.StartDate = date;
                }
                // check end date
                if (existFilm.FinishDate == DateTime.MinValue || existFilm.FinishDate < date)
                {
                    existFilm.FinishDate = date;
                }
                // update
                x_tblFilmTableAdapter.Update(existFilm);
            }
            return filmId;
        }

        private void insertSession(int cinemaID, int screenId, Dictionary<string, int> dictAdmit, int boRevenue, DateTime date)
        {
            foreach (int admits in dictAdmit.Values)
            {
                insertSession(cinemaID, screenId, admits, boRevenue, date);
            }
        }

        private void insertSession(int cinemaID, int screenId, int admits, int boRevenue, DateTime date)
        {
            int[] screen = new int[5] { 0, 0, 0, 0, 0 };
            screen[screenId - 1] = admits;
            x_tblSessionTableAdapter.Insert(cinemaID, screen[0], screen[1], screen[2], screen[3], screen[4], date);
        }

        private void updateTicketTypeData(ImportTicketTypeData cachedTicketTypeData, string strTicketType, int admits, int bo)
        {
            string ticketType = strTicketType.ToLower().Replace("total", "").Trim();
            if (ticketType.Equals("người lớn")
                || ticketType.Equals("adult"))
            {
                cachedTicketTypeData.Adult2D += admits;
                cachedTicketTypeData.Revenue2D += bo;
            }
            else if (ticketType.Equals("trẻ em")
               || ticketType.Equals("children"))
            {
                cachedTicketTypeData.Child2D += admits;
                cachedTicketTypeData.Revenue2D += bo;
            }
            else if (ticketType.Equals("người cao tuổi")
               || ticketType.Equals("senior"))
            {
                cachedTicketTypeData.Senior2D += admits;
                cachedTicketTypeData.Revenue2D += bo;
            }
            else if (ticketType.Equals("voucher")
               )
            {
                cachedTicketTypeData.CompTotal2D += admits;
                cachedTicketTypeData.Revenue2D += bo;
            }
            else if (ticketType.Equals("hssv")
               || ticketType.Equals("student"))
            {
                cachedTicketTypeData.Student2D += admits;
                cachedTicketTypeData.Revenue2D += bo;
            }
            else if (ticketType.Contains("vip"))
            {
                cachedTicketTypeData.VIP3D += admits;
                cachedTicketTypeData.Revenue3D += bo;
            }
            else if (ticketType.Contains("thường")
                || ticketType.Contains("thuong")
                || ticketType.Contains("standard"))
            {
                cachedTicketTypeData.Standard3D += admits;
                cachedTicketTypeData.Revenue3D += bo;
            }
        }
    }
}
